package services

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"time"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/utils"
)

type StocksService struct {
}

func (s *StocksService) CreateStocksNumber() string {
	stat := utils.GetDateParse(time.Now().Format("2006-01-02"))
	end := stat + 86400
	return fmt.Sprintf("%s%06d", time.Now().Format("20060102150405"), models.QueryStocksTimeSoltSeterCount(stat, end, )+1)
}

//新增盘点数据
func (s *StocksService) StocksCreateRecords(data *models.ErpStocks) (int64, error) {
	data.Number = s.CreateStocksNumber()
	if _, err := orm.NewOrm().Insert(data); err != nil {
		return 0, err
	}
	return data.Id, nil
}

//保存盘点明细
func (s *StocksService) SaveDetail(stocks_id int64, datatable string) error {
	if stocks_id == 0 || len(datatable) <= 0 {
		return errors.New("参数错误")
	}
	type DetailTemp struct {
		ReserveNum       int64  `json:"reserve_num"`
		ReserveRealNum   int64  `json:"reserve_real_num"`
		ReserveLossesNum int64  `json:"reserve_losses_num"`
		IsChange         int    `json:"is_change"`
		InventoryId      int64  `json:"inventory_id"`
		LotNumber        string `json:"lot_number"`       //批号
		ManufactureDate  int64  `json:"manufacture_date"` //生产日期
		ExpiryDate       int64  `json:"expiry_date"`      //有效日期
	}
	detail := make([]*DetailTemp, 0)
	if err := json.Unmarshal([]byte(datatable), &detail); err != nil {
		return err
	}
	to,_ := orm.NewOrm().Begin()
	for k, _ := range detail {
		value := detail[k]
		stocks_data := new(models.StocksData)
		stocks_data.Inventory = &models.ErpInventory{Id: value.InventoryId}
		stocks_data.Stocks = &models.ErpStocks{Id: stocks_id}
		//判断是否存在
		to.QueryTable(models.StocksDataTableName()).Filter("Stocks__Id", stocks_id).Filter("Inventory__Id", value.InventoryId).One(stocks_data)

		stocks_data.IsChange = value.IsChange
		stocks_data.PaperNumber = value.ReserveNum
		stocks_data.RealdiskNumber = value.ReserveRealNum
		stocks_data.ProfitlossNumber = value.ReserveLossesNum
		stocks_data.ExpiryDate = value.ExpiryDate
		stocks_data.ManufactureDate = value.ManufactureDate
		stocks_data.LotNumber = value.LotNumber
		if stocks_data.Sid > 0 {
			if _, err := to.Update(stocks_data, "PaperNumber", "RealdiskNumber", "ProfitlossNumber", "IsChange", "ManufactureDate", "ExpiryDate", "LotNumber"); err != nil {
				to.Rollback()
				return err
			}
		} else {
			if _, err := to.Insert(stocks_data); err != nil {
				to.Rollback()
				return err
			}
		}
	}
	to.Commit()
	return nil
}

//执行损益表
func (s *StocksService) SaveProfitLoss(depid, stocks_id int64, datatable string) error {

	if stocks_id == 0 || len(datatable) <= 0 {
		return errors.New("参数错误")
	}
	stocks, err := models.GetStocksById(stocks_id)
	if err != nil {
		return err
	}
	if stocks.Auditing == 1 {
		return errors.New("盘点已完成")
	}

	type DetailTemp struct {
		StocksDataId     int64 `json:"stocks_data_id"`
		ProfitlossNumber int64 `json:"profitloss_number"`
		InventoryId      int64 `json:"inventory_id"`
	}
	detail := make([]*DetailTemp, 0)
	if err := json.Unmarshal([]byte(datatable), &detail); err != nil {
		return err
	}
	flowingData := make([]*models.ErpFlowingData, 0)
	invSer := new(ErpInventoryService)
	to,_ := orm.NewOrm().Begin()
	if len(detail) > 0 {
		for k, _ := range detail {
			//开始更新库存
			inv := new(models.ErpInventory)
			to.QueryTable(models.ErpInventoryTableName()).Filter("id__eq", detail[k].InventoryId).Filter("DepartmentId", depid).One(inv)
			if inv.Id == 0 {
				to.Rollback()
				return errors.New("找不到库存信息")
			}
			//设置流水明细
			flowing := new(models.ErpFlowingData)
			if detail[k].ProfitlossNumber > 0 {
				flowing.Typeid = 5 //盘盈入库
				flowing.StorageNum = detail[k].ProfitlossNumber
			} else {
				flowing.Typeid = 6 //盘亏出库
				flowing.StorageNum = 0 - detail[k].ProfitlossNumber
			}
			flowing.DepartmentId = inv.DepartmentId
			flowing.Products = inv.Products
			flowing.Acceptance = inv.Acceptance
			flowing.Snd = inv.Snd
			flowing.InventoryId = inv.Id
			flowing.PrimaryStorageNum = inv.Inventory
			flowing.PurchaseUpNo = stocks.Number
			flowingData = append(flowingData, flowing)

			//更新库存
			if err := invSer.UpdateErpInventory(to, inv, detail[k].ProfitlossNumber); err != nil {
				to.Rollback()
				return err
			}
		}
		//写入流水明细
		flSer := new(ErpFlowingService)
		if err := flSer.SaveErpFlowingData(to, &models.ErpFlowing{Id: 0}, flowingData); err != nil {
			to.Rollback()
			return err
		}
	}
	//更新盘点主表
	stocks.Auditing = 1
	if _, err := to.Update(stocks, "Auditing"); err != nil {
		to.Rollback()
		return err
	}
	to.Commit()
	return nil
}

//查看盘点信息
func (s *StocksService) StocksDetail(id int64) (*models.ErpStocks, error) {

	return nil, nil
}



//删除盘点数据
func (s *StocksService) StocksDelete(id int64) error {
	to,_ := orm.NewOrm().Begin()

	stock := &models.ErpStocks{Id: id}

	if err := to.Read(stock); err != nil { //查询是否存在记录信息
		to.Rollback()
		return err
	}

	if stock.Auditing == 1 {
		return errors.New("已通过审核的数据不允许删除")
	}

	if _, err := to.Delete(stock); err != nil {
		to.Rollback()
		return err
	}
	//删除副表内容
	if _, err := to.QueryTable(models.StocksDataTableName()).Filter("stocks_id", id).Delete(); err != nil {
		to.Rollback()
		return err
	}

	to.Commit()

	return nil
}


//判断商品是否盘点中
func StocksCheckIng(products_id int64, u *models.BackendUser) error {
	count,_ := orm.NewOrm().QueryTable(models.StocksTableName()).Filter("department_id", u.DepartmentId).Filter("Products__Id", products_id).Filter("Auditing", 0).Count()
	if count > 0 {
		return errors.New("商品盘中点，不允许操作")
	}
	return nil
}